package com.photoeditor.demo.app;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.SystemClock;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.android.billingclient.api.BillingClient;
import com.android.videolib.MediaCodecHelper;
import com.android.videolib.VideoCooker;
import com.billing.base.BillingManager;
import com.billing.base.SimpleBillingUpdateListener;
import com.billing.base.SkuWithType;
import com.billing.base.svip.SVipManager;
import com.common.base.ComponentContext;
import com.common.base.ExceptionManager;
import com.common.base.UncaughtExceptionHandler;
import com.common.base.app.BaseApplication;
import com.common.base.log.LogUtil;
import com.common.base.log.RLog;
import com.common.base.service.ScheduleJobService;
import com.common.base.utils.AppUtils;
import com.common.base.utils.DebugUtil;
import com.common.base.utils.DeviceUtils;
import com.common.base.utils.PlatformUtil;
import com.common.base.utils.ProcessUtils;
import com.common.commercialize.channel.BuyUserManager;
import com.common.commercialize.sdk.CommercializeConfig;
import com.common.commercialize.sdk.CommercializeSDK;
import com.common.commercialize.sdk.CrashHandler;
import com.common.commercialize.strategy.StrategyManager;
import com.common.statistics.StatisticsManager;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.https.HttpsUtils;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.photoeditor.BuildConfig;
import com.photoeditor.R;
import com.photoeditor.demo.ad.AdKeyConstant;
import com.photoeditor.demo.ad.CameraStrategyConstant;
import com.photoeditor.demo.db.DataManager;
import com.photoeditor.demo.model.image.gl.ThreadPool;
import com.photoeditor.demo.imageloader.ImageLoader;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.model.store.module.preload.PreloadManager;
import com.photoeditor.demo.model.store.module.preload.UpdateManager;
import com.photoeditor.demo.model.share.ShareImageDialogHelp;
import com.photoeditor.demo.model.store.listener.ApplyActivityListener;
import com.photoeditor.demo.model.store.module.HomeOnlineManager;
import com.photoeditor.demo.model.store.module.StoreOnlineManager;
import com.photoeditor.demo.model.subscribe.manager.AppVipManager;
import com.photoeditor.demo.model.subscribe.manager.SkuManager;
import com.photoeditor.demo.model.subscribe.strategy.SVipStrategyManager;
import com.photoeditor.demo.statistics.NotifyStoreUpdateStatisticBean;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.statistics.Umeng;
import com.photoeditor.demo.util.AppFrontBackHelper;
import com.photoeditor.demo.util.AsyncTaskDefaultSerialExecutor;
import com.photoeditor.demo.util.FileUtil;
import com.photoeditor.demo.util.Gif2VideoUtils;
import com.photoeditor.demo.util.hook.ActivityManagerHook;
import com.rey.material.app.ThemeManager;
import com.squareup.leakcanary.LeakCanary;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import butterknife.ButterKnife;
import me.xiaopan.sketch.Sketch;
import me.xiaopan.sketch.cache.LruMemoryCache;
import okhttp3.OkHttpClient;

import static com.common.base.ComponentContext.getContext;

//import com.photoeditor.demo.push.PushNotificationManager;

/**
 * Created by winn on 17/3/3.
 */

public class AppApplication extends BaseApplication implements BuyUserManager.BuyUserListener, CrashHandler.ExceptionHandler {
    private static final String TAG = AppApplication.class.getName();
    private static AppApplication sApp;

//    private static HomeWatcherReceiver sHomeKeyReceiver = null;
//    private static HomeBtnReceiver sHomeBtnReceiver = null;

    /**
     * 首次启动，数据延时初始化时间
     */
    private static final int DATA_INIT_DELAY_TIME = 2000;

    public static long intoAppTime = 0;

    //    public final static String PROCESS_NAME_GALLERY = "separate";
    public final static String PROCESS_NAME_DAEMON = "process2";
    public final static String PROCESS_NAME_UMENG = "channel";
    public final static String PROCESS_NAME_DOWNLOAD = "filedownloader";
    public final static String PROCESS_NAME_LEAKCANARY = "leakcanary";

    public final static int PROCESS_TYPE_UNKNOW = -1;
    public final static int PROCESS_TYPE_MAIN = 0;
    //    public final static int PROCESS_TYPE_GALLERY = 1;
    public final static int PROCESS_TYPE_DAEMON = 2;
    public final static int PROCESS_TYPE_UMENG = 3;
    public final static int PROCESS_TYPE_DOWNLOAD = 4;
    public final static int PROCESS_TYPE_LEAKCANARY = 5;

    private boolean mIsActiveFromBackground = false;
    private boolean mShowSplashAd = false;

    private CopyOnWriteArrayList<BuyUserManager.BuyUserListener> mBuyUserListeners = new CopyOnWriteArrayList<>();

    public static AppApplication getApplication() {
        return sApp;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        ComponentContext.setContext(this);

//        if (LeakCanary.isInAnalyzerProcess(this)) {
//            // This process is dedicated to LeakCanary for heap analysis.
//            // You should not init your app in this process.
//            return;
//        }

        // 这里调用系统服务先行测试，若失败，意味系统正在关闭或重启，不继续操作
        try {
            AppUtils.getVersionCode(ComponentContext.getContext());
        } catch (RuntimeException e) {
            return;
        }

        if (TestUser.isTestUser() || DebugUtil.isDebuggable()) {
            LogUtil.setFileLogEnable(true);
            initUncautExceptionHandler();
        }
        ButterKnife.setDebug(DebugUtil.isDebuggable());
        //LeakCanary.install(this);

        //替换系统AsyncTask的Executor,ediText会造成内存泄漏 使用完之后清空任务
        try {
            Class asyncTaskManager = Class.forName("android.os.AsyncTask");
            Method setDefaultExecutor = asyncTaskManager.getMethod("setDefaultExecutor", Executor.class);
            setDefaultExecutor.invoke(android.os.AsyncTask.class, AsyncTaskDefaultSerialExecutor.getInstance());
        } catch (Exception e) {
            e.printStackTrace();
        }

        ThemeManager.init(this, 2, 0, null);
        setSketchMemoryCacheSize();

        int processType = getProcessType();
        // NOTE: 相册页面不初始化数据及广告
        if (processType == PROCESS_TYPE_MAIN) {
            // Umeng初始化
            Umeng.initStatistics(this, BuyUserManager.getInstance().getBuyUserType());
            StatisticsManager.setLogSwitch(TestUser.getTestFile() != null || DebugUtil.isDebuggable());
            initAd();

            initVip();

            initData();

            // 监听接收详情页跳转的界面生命周期
            registerActivityLifecycleCallbacks(ApplyActivityListener.getInstance());

            AppFrontBackHelper.getInstant().register(this);

//            com.common.base.utils.thread.ThreadPool.runUITask(new Runnable() {
//                @Override
//                public void run() {
//                    DaemonClient.getInstance().startForeground(ComponentContext.getContext(), true, true);
//                }
//            }, 5000);

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
            loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
            loggingInterceptor.setColorLevel(Level.INFO);
            builder.addInterceptor(loggingInterceptor);

            builder.readTimeout(3*OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
            builder.writeTimeout(3*OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
            builder.connectTimeout(3*OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);

            HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
            builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);
            OkGo.getInstance().setOkHttpClient(builder.build());
        }

        mActivityStartTimes = new HashMap<>();

        statisics();
    }

    /**
     * 获取系统的SP组件
     *
     * @param name
     * @param mode
     * @return
     */
    public SharedPreferences getSystemPreferences(String name, int mode) {
        return super.getSharedPreferences(name, mode);
    }

    private void initAd() {

        CommercializeSDK.TestUser.isTestUser();
        CommercializeConfig config = new CommercializeConfig.Builder()
                .setTest(BuildConfig.TEST)
                .setBatmobiKey(AdKeyConstant.BATMOBI_APPKEY)
                .setAdmobAppKey(AdKeyConstant.ADMOB_APPKEY)
                .setUnityAdsGameId(AdKeyConstant.UNITY_GAMEID)
                .setAppsflyerKey(AdKeyConstant.APPSFLYER_DEV_KEY)
                .setAdStrategyResUrl(AdKeyConstant.APP_STRATEGY_URL)
                .setAdUnitPriorityUrl(AdKeyConstant.APP_PRIORITY_URL)
                .setSubEventUrl(AdKeyConstant.APP_SUBEVENT_URL)
                .build();
        //评分引导
        StrategyManager.getInstance().addId(
                CameraStrategyConstant.FUN_ID_RATE_DIALOG,
                CameraStrategyConstant.FUN_ID_SVIP,
                CameraStrategyConstant.FUN_ID_SKU);
        CommercializeSDK.setup(this, config, this);

        CommercializeSDK.getInstance().setCrashExceptionHandler(this);

        if (ProcessUtils.isMainProcess(this)) {

            ScheduleJobService.startScheduleJobService(this);
            ScheduleJobService.registerJob(new StatisticsUtils.OfflineStatistics());

        }

        setBuyUser();

    }

    private void initVip() {
        /**
         * svip初始化
         */
        BillingManager.setDebug(TestUser.isTestUser());
        BillingManager.getInstance().addBillingUpdatesListener(new SimpleBillingUpdateListener() {

            @Override
            public void onBillingClientSetupFinished() {
                super.onBillingClientSetupFinished();
                BillingManager.getInstance().removeBillingUpdatesListener(this);
                // 设置SVIP的付费sku
                String[] skuInfos = SkuManager.getSkuInfo(SkuManager.TYPE_ALL);
                if (skuInfos != null) {
                    SVipManager.getInstance().setSku(skuInfos);

                    // 预加载付费信息
                    List<SkuWithType> skuWithTypes = null;
                    SkuWithType skuWithType;
                    for (String sku : skuInfos) {
                        if (skuWithTypes == null) {
                            skuWithTypes = new ArrayList<>();
                        }
                        skuWithType = new SkuWithType(sku, BillingClient.SkuType.SUBS);
                        skuWithTypes.add(skuWithType);
                    }

                    if (skuWithTypes != null && !skuWithTypes.isEmpty()) {
                        BillingManager.getInstance().preloadSkuDetails(skuWithTypes);
                    }
                }
            }
        });
        // 初始化付费管理类
        BillingManager.getInstance().setup(ComponentContext.getContext(), BuildConfig.billingPublishKey);
        SVipStrategyManager.getInstance().init();
        BillingManager.getInstance().startConnect();

        StatisticsUtils.updateUserProperty(StatisticsConstant.PROPERTY_KEY_IF_SUB,
                AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB);
    }

    private void initData() {
        SPDataManager.init();
        // 耗时初始化操作需要放到异步线程延时初始化
        // 判断是否第一次安装app，如果是，耗时数据初始化需要异步延迟加载
//        if (ProcessUtils.isMainProcess(this)) {
        // 目前有启动页，数据初始化放在主线程，不会对启动速度有太大影响
//            if (SPDataManager.isFirstStart()) {
//                com.common.base.utils.thread.ThreadPool.runOnNonUIThread(new Runnable() {
//                    @Override
//                    public void run() {
        doInit();
//                    }
//                }, DATA_INIT_DELAY_TIME);
//            } else {
//                doInit();
//            }
//        }
    }

    private void doInit() {
        try {
            doInitAsync();
        } catch (Exception e) {
        }
    }

    private void doInitAsync() {
        com.common.base.utils.thread.ThreadPool.runOnNonUIThread(new Runnable() {

            @Override
            public void run() {
                try {
//                    Umeng.initPush(getContext());

                    StoreOnlineManager.getInstance().loadData();
                    HomeOnlineManager.getInstance().loadData();
                    DataManager.getInstance().initData();
                    PreloadManager.getInstance().preloadData();
                    UpdateManager.getInstance();
//                    PushNotificationManager.getInstance().setup();

                    DataManager.getInstance().loadInstalledResData();
                    Gif2VideoUtils.checkIsSupport1080P();
                    VideoCooker.init(getContext());
                    ShareImageDialogHelp.deleteInsImg();
//                    ShareAppDialogHelp.initDefaultShareImg();
                    MediaCodecHelper.getInstance().init();
                    if (!SPDataManager.isBasicVideoInit()) {
                        if (FileUtil.copyRawToFileSystem(R.raw.basic_video_30_no_audio, FileUtil.BASIC_VIDEO_30_FILE_PATH)
                                && FileUtil.copyRawToFileSystem(R.raw.basic_video_50_no_audio, FileUtil.BASIC_VIDEO_50_FILE_PATH)) {
                            SPDataManager.setBasicVideoInit();
                        }
                    }

                    //留存率统计
                    Date current = new Date(System.currentTimeMillis());
                    Date lastTime = new Date(SPDataManager.getRetentionLastTime());
                    if (current.getDate() != lastTime.getDate() || current.getMonth() != lastTime.getMonth()) {
                        StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_RETENTION,
                                StatisticsConstant.UMENG_CUSTOM_EVENT_ALL, StatisticsConstant.UMENG_CUSTOM_EVENT_RETENTION);
                        SPDataManager.setRetentionLastTime(System.currentTimeMillis());
                    }

                    if (SpUtils.obtain().getBoolean("st_n_op", true)) {
                        SpUtils.obtain().save("st_n_op", false);
                        StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_RETENTION,
                                StatisticsConstant.UMENG_CUSTOM_EVENT_ALL, StatisticsConstant.UMENG_CUSTOM_EVENT_NEW);
                        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_NEW_OPEN);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, DATA_INIT_DELAY_TIME);
    }

    @Override
    protected void attachBaseContext(Context base) {
        sApp = this;
        super.attachBaseContext(base);
        MultiDex.install(this);
        fixFinalizeBug();
        ActivityManagerHook.hookActivityManagerNative();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        ImageLoader.onLowMemory();
    }


    private void setBuyUser() {
        updateSettings4Bussiness();
    }

    public void updateSettings4Bussiness() {

    }

    @Override
    public void setBuyUser(String buyUserSource, int userType) {
        setBuyUser();
        for (BuyUserManager.BuyUserListener listener : mBuyUserListeners) {
            listener.setBuyUser(buyUserSource, userType);
        }
    }

    private void initUncautExceptionHandler() {
        ExceptionManager.getInstance().initiate(this);
        UncaughtExceptionHandler.getInstance(this).register();
        UncaughtExceptionHandler.getInstance(this).setInterceptor(new UncaughtExceptionHandler.UncaughtExceptionInterceptor() {

            @Override
            public boolean onInterceptExceptionBefore(Thread t, Throwable ex) {
                RLog.e("Exception", ex.getMessage(), ex);
                RLog.flush();
                File pathFile = new File(getExternalCacheDir() + "/bug.log");
                FileWriter fileWriter = null;
                try {
                    fileWriter = new FileWriter(pathFile);
                    fileWriter.write(ex.toString());
                    StackTraceElement[] stackTrace = ex.getStackTrace();
                    for (StackTraceElement stackTraceElement : stackTrace) {
                        fileWriter.write(stackTraceElement.toString());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (fileWriter !=null) {
                        try {
                            fileWriter.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                SystemClock.sleep(500);
                return false;
            }

            @Override
            public boolean onInterceptExceptionAfter(Thread t, Throwable ex) {
                return false;
            }
        });
    }

    /**
     * 版本号
     *
     * @return 版本号
     */
    public static int getVersionCode() {
        return AppUtils.getVersionCodeByPkgName(getContext(), getContext().getPackageName());
    }

    @Override
    public void startActivity(Intent intent) {
        if (null != intent) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName component = intent.getComponent();        //处理admob广告多进程打开异常
            if (null != component && "com.google.android.gms.ads.AdActivity".equals(component.getClassName())) {
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            }
        }
        try {
            super.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private ThreadPool mThreadPool;

    public ThreadPool getThreadPool() {
        if (mThreadPool == null) {
            mThreadPool = new ThreadPool();
        }
        return mThreadPool;
    }

    private Map<String, Long> mActivityStartTimes;

    @Override
    public void dispatchActivityStartedInner(Activity activity) {
        super.dispatchActivityStartedInner(activity);
        if (activity != null) {
            mActivityStartTimes.put(activity.getClass().getName(), System.currentTimeMillis());
        }
    }

    @Override
    public void dispatchActivityStoppedInner(Activity activity) {
        super.dispatchActivityStoppedInner(activity);
        if (activity != null) {
            Long startTime = mActivityStartTimes.get(activity.getClass().getName());
            if (startTime != null && startTime != 0) {
                int time = (int) ((System.currentTimeMillis() - startTime) / 1000)
                        + SpUtils.obtain().getInt(activity.getClass().getName(), 0);
                SpUtils.obtain().save(activity.getClass().getName(), time);
            }
        }
        if (isBackground()) {
            ImageLoader.clearMemoryCache();
        }
    }

    /**
     * 暂存页面临时保存在内存中，暂存页面负责销毁
     */
    private Bitmap mStashPicture;

    public void setStashPicture(Bitmap bitmap) {
        mStashPicture = bitmap;
    }

    public Bitmap getStashPicture() {
        return mStashPicture;
    }

    public void recycleStashPicture() {
        mStashPicture = null;
    }

    /**
     * 分享页面临时保存在内存中，分享页面负责销毁
     */
    private Bitmap mSharePicture;

    public void setSharePicture(Bitmap bitmap) {
        mSharePicture = bitmap;
    }

    public Bitmap getSharePicture() {
        return mSharePicture;
    }

    public void recycleSharePicture() {
        mSharePicture = null;
    }

    /**
     * 主进程及相册进程返回false，其他都返回true
     *
     * @return
     */
    public int getProcessType() {
        String pro = ProcessUtils.myProcessName(this);
        int ret = PROCESS_TYPE_UNKNOW;
        if (!TextUtils.isEmpty(pro)) {
            if (!pro.contains(":")) {
                ret = PROCESS_TYPE_MAIN;
            } /*else if (pro.endsWith(PROCESS_NAME_GALLERY)) {
                ret = PROCESS_TYPE_GALLERY;
            } */ else if (pro.endsWith(PROCESS_NAME_DAEMON)) {
                ret = PROCESS_TYPE_DAEMON;
            } else if (pro.endsWith(PROCESS_NAME_DOWNLOAD)) {
                ret = PROCESS_TYPE_DOWNLOAD;
            } else if (pro.endsWith(PROCESS_NAME_LEAKCANARY)) {
                ret = PROCESS_TYPE_LEAKCANARY;
            } else if (pro.endsWith(PROCESS_NAME_UMENG)) {
                ret = PROCESS_TYPE_UMENG;
            }
        }
        return ret;
    }

    private void statisics() {
        // 统计进程情况
        int processType = getProcessType();
        String processName = "unknown";
        switch (processType) {
            case PROCESS_TYPE_MAIN:
                processName = "main";
                break;
//            case PROCESS_TYPE_GALLERY:
//                processName = PROCESS_NAME_GALLERY;
//                break;
            case PROCESS_TYPE_DAEMON:
                processName = PROCESS_NAME_DAEMON;
                break;
            case PROCESS_TYPE_UMENG:
                processName = PROCESS_NAME_UMENG;
                break;
            case PROCESS_TYPE_DOWNLOAD:
                processName = PROCESS_NAME_DOWNLOAD;
                break;
            case PROCESS_TYPE_LEAKCANARY:
                processName = PROCESS_NAME_LEAKCANARY;
                break;
            default:
        }
        com.common.statistics.StatisticsUtils.statisics(StatisticsConstant.UMENG_CUSTOM_EVENT_PREFIX_FUNCTION, "process", "name", processName);
    }

    private void fixFinalizeBug() {
        if (PlatformUtil.version() == PlatformUtil.VERSION_CODES.KITKAT) {
            try {
                Class clazz = Class.forName("java.lang.Daemons$FinalizerWatchdogDaemon");
                Method method = clazz.getSuperclass().getDeclaredMethod("stop");
                method.setAccessible(true);

                Field field = clazz.getDeclaredField("INSTANCE");
                field.setAccessible(true);

                method.invoke(field.get(null));
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    private void setSketchMemoryCacheSize() {
        // 设置默认最大容量是 2 个屏幕像素数
        try {
            int screenSize = DeviceUtils.getRealScreenHeightPx() * DeviceUtils.getScreenWidthPx() * 4;
            final int memoryCacheMaxSize = screenSize * 2;
            Sketch.with(ComponentContext.getContext()).getConfiguration().setMemoryCache(new LruMemoryCache(ComponentContext.getContext(), memoryCacheMaxSize));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        ImageLoader.onTrimMemroy(level);
    }

    //商店内容更新通知栏显示的资源包名   进入详情页时赋值
    private NotifyStoreUpdateStatisticBean mNotifyStoreContentStatisticBean;

    public NotifyStoreUpdateStatisticBean getNotifyStoreContentStatisticBean() {
        return mNotifyStoreContentStatisticBean;
    }

    public void setNotifyStoreContentStatisticBean(NotifyStoreUpdateStatisticBean bean) {
        mNotifyStoreContentStatisticBean = bean;
    }

    @Override
    public boolean catchException(Thread thread, Throwable throwable) {
        // 这里拦截主线程的一些异常，避免崩溃，返回true拦截
        // 具体方式参考商业化代码
        //java.lang.ArithmeticException: divide by zero
//        if (throwable instanceof java.lang.ArithmeticException) {
//            if (CrashHandler.getThrowableMessage(throwable).contains("divide by zero")
//                    && CrashHandler.getThrowableStackTrace(throwable, 0).contains("com.photoeditor.demo.ui.entrance")) {
//                return true;
//            }
//        }
        return false;
    }

    public boolean isActiveFromBackground() {
        return mIsActiveFromBackground;
    }

    public void setActiveFromBackground(boolean activeFromBackground) {
        this.mIsActiveFromBackground = activeFromBackground;
    }

    public boolean isShowSplashAd() {
        return mShowSplashAd;
    }

    public void setShowSplashAd(boolean showSplashAd) {
        mShowSplashAd = showSplashAd;
    }

    public void addBuyUserListener(BuyUserManager.BuyUserListener listener) {
        if (!mBuyUserListeners.contains(listener)) {
            mBuyUserListeners.add(listener);
        }
    }

    public void removeBuyUserListener(BuyUserManager.BuyUserListener listener) {
        mBuyUserListeners.remove(listener);
    }
}
